import { asyncRoutes, constantRoutes } from "@/router";
import { findUserMenu } from "@/api/user.js";
import Layout from "@/layout";
import ModulePermission from "panna-module-permission";
import ModuleFlowWork from "panna-module-workflow";
import ModuleSampling from "panna-module-sampling";
import ModuleMessage from "panna-module-message";
import ModeleSystem from 'panna-module-system'
import ModeleSysBusiness from 'panna-module-sysbusiness'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role));
  } else {
    return true;
  }
}

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generateMenu(routes, data, buttonMap) {
  const authMap = buttonMap || new Map();
  data.forEach((item) => {
    let menu = {};
    item.permissionButtons.forEach((operate) => {
      authMap.set(`${item.frontUrl}/${operate.eName}`, true);
    });
    if (item.frontUrl.toLocaleLowerCase() === "dashboard") {
      menu = {
        path: "/",
        component: Layout,
        redirect: "/" + item.frontUrl,
        children: [
          {
            path: item.frontUrl,
            component: (resolve) =>
              require([`@/${item.component}.vue`], resolve),
            name: "dashboard",
            meta: { title: item.name, icon: item.icon, affix: true },
          },
        ],
      };
    } else if (item.parentId === "0" && item.component !== "#") {
      // 如果parentId=0且component不等于#,说明是一级菜单,并且一级菜单可直接显示页面
      menu = {
        path: "/" + item.frontUrl,
        component: Layout,
        children: [
          {
            path: "",
            component: (resolve) =>
              require([`@/${item.component}.vue`], resolve),
            name: "menu_" + item.parentId + "_" + item.id,
            hidden: item.isShow !== 1,
            meta: { title: item.name, icon: item.icon },
          },
        ],
      };
    } else if (item.parentId === "0" && item.component === "#") {
      // 如果parentId=0且component等于#,说明是一级菜单,并且一级菜单不可直接显示页面,子集才能直接显示页面
      menu = {
        path: "/" + item.frontUrl,
        component: Layout,
        redirect: item.children[0]
          ? "/" + item.children[0].redirect
          : "dashboard", // 如果输出了dashboard,说明子集全部被限制了
        // name: item.frontUrl,
        name: "menu_" + item.parentId + "_" + item.id,
        meta: { title: item.name, icon: item.icon },
        hidden: item.isShow !== 1,
        children: [],
      };
    } else {
      let componentPath = (resolve) =>
        require([`@/${item.component}.vue`], resolve);
      componentPath = ModulePermission.Api["ModuleFoundation"].getMenuComponent(
        componentPath,
        ModulePermission,
        item.component
      );
      componentPath = ModuleFlowWork.Api["ModuleFoundation"].getMenuComponent(
        componentPath,
        ModuleFlowWork,
        item.component
      );
      componentPath = ModuleSampling.Api["ModuleFoundation"].getMenuComponent(
        componentPath,
        ModuleSampling,
        item.component
      );
      componentPath = ModuleMessage.Api["ModuleFoundation"].getMenuComponent(
        componentPath,
        ModuleMessage,
        item.component
      );
      componentPath = ModeleSystem.Api["ModuleFoundation"].getMenuComponent(
        componentPath,
        ModeleSystem,
        item.component
      );
      componentPath = ModeleSysBusiness.Api["ModuleFoundation"].getMenuComponent(
        componentPath,
        ModeleSysBusiness,
        item.component
      );
      menu = {
        path: item.frontUrl,
        component: componentPath,
        hidden: item.isShow !== 1,
        children: [],
        // name: item.frontUrl,
        name: "menu_" + item.parentId + "_" + item.id,
        meta: { title: item.name, icon: item.icon },
      };
    }

    if (item.children && item.children.length > 0) {
      generateMenu(menu.children, item.children, authMap);
    }
    routes.push(menu);
  });
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = [];

  routes.forEach((route) => {
    const tmp = { ...route };
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
      res.push(tmp);
    }
  });

  return res;
}

const state = {
  routes: [],
  addRoutes: [],
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  },
  SET_MENU_OPERATE: (state, operateMap) => {
    state.addoperateMap = operateMap;
    state.operateMap = operateMap;
  },
};

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise((resolve) => {
      const loadMenuData = [];
      // 先查询后台并返回左侧菜单数据并把数据添加到路由
      findUserMenu()
        .then((response) => {
          let data = response;
          if (response.code !== 200) {
            console.log("菜单数据加载异常");
            // throw new Error('菜单数据加载异常')
          } else {
            data = response.data;
            Object.assign(loadMenuData, data);
            const tempAsyncRoutes = Object.assign([], asyncRoutes);
            // 获取授权菜单和按钮
            const authbuttons = new Map();
            // tempAsyncRoutes = asyncRoutes
            generateMenu(tempAsyncRoutes, loadMenuData, authbuttons);
            let accessedRoutes;
            if (roles.includes("admin")) {
              // alert(JSON.stringify(asyncRoutes))
              accessedRoutes = tempAsyncRoutes || [];
            } else {
              accessedRoutes = filterAsyncRoutes(tempAsyncRoutes, roles);
            }
            commit("SET_ROUTES", accessedRoutes);
            commit("SET_MENU_OPERATE", authbuttons);
            resolve(accessedRoutes);
          }
          // generaMenu(asyncRoutes, data)
        })
        .catch((error) => {
          console.log(error);
        });
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
